<template>
  <CustomScrollbar class="search-scroll">
    <div class="search">
    <!-- 无搜索内容时的状态 -->
    <div v-if="!searchQuery" class="empty-state">
      <div class="search-tips">
        <h2>搜索音乐</h2>
        <p>使用上方搜索栏查找您喜欢的歌曲、歌手或专辑</p>
      </div>
      
      <h3 class="section-title">热门搜索</h3>
      <div class="hot-searches">
        <span 
          v-for="term in hotSearches" 
          :key="term"
          class="hot-search-tag"
          @click="triggerSearch(term)"
        >
          {{ term }}
        </span>
      </div>
      
      <h3 class="section-title">浏览分类</h3>
      <div class="browse-categories">
        <div 
          v-for="category in categories" 
          :key="category.id"
          class="browse-card"
          :style="{ backgroundColor: category.color }"
          @click="searchByCategory(category)"
        >
          <span class="category-emoji">{{ category.emoji }}</span>
          <h4>{{ category.name }}</h4>
        </div>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div v-else class="search-results">
      <!-- 搜索中状态 -->
      <div v-if="isSearching" class="loading-state">
        <div class="loading-spinner"></div>
        <p>搜索中...</p>
      </div>

      <!-- 有搜索结果 -->
      <div v-else-if="searchResults.length > 0">
        <h2 class="results-title">搜索结果 "{{ searchQuery }}"</h2>
        <p class="results-count">找到 {{ searchResults.length }} 首歌曲</p>
        
        <!-- 歌曲列表 -->
        <div class="songs-table">
          <div class="table-header">
            <div class="header-index">#</div>
            <div class="header-title">标题</div>
            <div class="header-category">分类</div>
            <div class="header-duration">时长</div>
            <div class="header-actions">操作</div>
          </div>
          
          <div class="table-body">
            <div 
              v-for="(song, index) in searchResults" 
              :key="song.id"
              class="song-row"
              @click="playMusic(song)"
            >
              <div class="song-index">{{ index + 1 }}</div>
              
              <div class="song-info">
                <img v-if="song.cover" :src="song.cover" :alt="song.title" class="song-thumbnail">
                <MusicIcon v-else :size="48" class="song-thumbnail" />
                <div class="song-details">
                  <div class="song-title">{{ song.title }}</div>
                  <div class="song-artist">{{ song.artist }}</div>
                </div>
              </div>
              
              <div class="song-category">
                <span class="category-tag" :style="{ backgroundColor: getCategoryColor(song.category) }">
                  {{ song.category }}
                </span>
              </div>
              
              <div class="song-duration">{{ formatDuration(song.duration) }}</div>
              
              <div class="song-actions" @click.stop>
                <button 
                  class="action-btn favorite-btn" 
                  @click="toggleFavorite(song)"
                  :class="{ 'favorited': isFavorite(song.id) }"
                >
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                    <path d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"/>
                  </svg>
                </button>
                <button class="action-btn play-btn" @click="playMusic(song)">
                  ▶
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 无搜索结果 -->
      <div v-else class="no-results">
        <div class="no-results-icon">🎵</div>
        <h3>没有找到 "{{ searchQuery }}"</h3>
        <p>请尝试不同的搜索词或浏览下方分类</p>
        
        <div class="suggested-categories">
          <h4>或者试试这些分类</h4>
          <div class="category-suggestions">
            <span 
              v-for="category in categories.slice(0, 4)" 
              :key="category.id"
              class="category-suggestion"
              @click="searchByCategory(category)"
            >
              {{ category.emoji }} {{ category.name }}
            </span>
          </div>
        </div>
      </div>
    </div>
    </div>
  </CustomScrollbar>
</template>

<script>
import MusicIcon from '@/components/MusicIcon.vue'
import CustomScrollbar from '@/components/CustomScrollbar.vue'
import { musicAPI, categoryAPI, playlistAPI } from '@/utils/api'

export default {
  components: {
    MusicIcon,
    CustomScrollbar
  },
  name: 'SearchView',
  data() {
    return {
      searchQuery: this.$route.query.q || '',
      isSearching: false,
      searchResults: [],
      favorites: [1, 3], // 模拟收藏的歌曲ID
      hotSearches: [
        '周杰伦', '稻香', '青花瓷', '说好不哭', '七里香',
        '流行歌曲', '经典老歌', '最新音乐'
      ],
      categories: [
        { id: 1, name: '流行', color: '#1DB954', emoji: '🎵' },
        { id: 2, name: '摇滚', color: '#E22134', emoji: '🎸' },
        { id: 3, name: '古典', color: '#8056d3', emoji: '🎼' },
        { id: 4, name: '爵士', color: '#ba5d07', emoji: '🎷' },
        { id: 5, name: '民谣', color: '#27856a', emoji: '🪕' },
        { id: 6, name: '电子', color: '#2d46b9', emoji: '🎛️' },
        { id: 7, name: '说唱', color: '#e8115b', emoji: '🎤' },
        { id: 8, name: '轻音乐', color: '#608108', emoji: '🎹' }
      ]
    }
  },
  async mounted() {
    // 加载收藏列表
    await this.$store.dispatch('player/loadFavorites')
    
    // 如果URL中有查询参数，自动执行搜索
    if (this.searchQuery) {
      this.performSearch()
    }
  },
  watch: {
    '$route.query.q': {
      immediate: true,
      handler(newQuery) {
        if (newQuery && newQuery !== this.searchQuery) {
          this.searchQuery = newQuery
          this.performSearch()
        }
      }
    }
  },
  methods: {
    triggerSearch(term) {
      this.$router.push({ path: '/search', query: { q: term } })
    },
    
    async performSearch() {
      if (!this.searchQuery.trim()) {
        this.searchResults = []
        return
      }

      this.isSearching = true
      
      try {
        // 使用真实API搜索音乐
        const response = await musicAPI.getAllMusic(0, 50) // 获取更多音乐用于搜索
        
        if (response.music && response.music.length > 0) {
          const query = this.searchQuery.toLowerCase()
          
          // 在真实数据中搜索
          this.searchResults = response.music
            .filter(music => 
              music.name.toLowerCase().includes(query) ||
              music.singer.toLowerCase().includes(query) ||
              (music.category?.name && music.category.name.toLowerCase().includes(query))
            )
            .map(music => ({
              id: music.musicId,
              title: music.name, // SearchView使用title字段
              artist: music.singer, // SearchView使用artist字段
              album: music.album || '未知专辑',
              category: music.category?.name || '未知分类',
              duration: music.duration,
              cover: this.buildCoverUrl(music.coverPath),
              filePath: this.buildAudioUrl(music.filePath)
            }))
          
          console.log('搜索结果:', this.searchResults.length, '首歌曲')
        } else {
          console.warn('API返回空数据')
          this.searchResults = []
        }
      } catch (error) {
        console.error('搜索失败:', error)
        this.searchResults = []
      } finally {
        this.isSearching = false
      }
    },
    
    searchByCategory(category) {
      this.$router.push({ path: '/search', query: { q: category.name } })
    },
    
    formatDuration(seconds) {
      // 处理各种输入情况
      if (seconds === null || seconds === undefined || seconds === 0) return '-'
      
      // 确保是数字类型
      const numSeconds = Number(seconds)
      if (isNaN(numSeconds) || numSeconds < 0) return '-'
      
      // 计算分钟和秒
      const minutes = Math.floor(numSeconds / 60)
      const remainingSeconds = Math.floor(numSeconds % 60)
      
      // 格式化输出
      if (minutes >= 60) {
        // 超过1小时的情况
        const hours = Math.floor(minutes / 60)
        const remainingMinutes = minutes % 60
        return `${hours}:${remainingMinutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
      } else {
        // 普通情况：分:秒
        return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
      }
    },
    
    async playMusic(song) {
      try {
        console.log('播放音乐:', song.title)
        
        // 构建播放列表（搜索结果）
        const playlist = this.searchResults.map(s => ({
          musicId: s.id,
          id: s.id,
          title: s.title,
          name: s.title,
          artist: s.artist,
          singer: s.artist,
          coverPath: s.cover,
          cover: s.cover,
          duration: s.duration,
          filePath: s.filePath,
          src: s.filePath
        }))
        
        // 设置播放列表
        this.$store.commit('player/SET_PLAYLIST', playlist)
        
        // 找到当前音乐在播放列表中的索引
        const currentIndex = playlist.findIndex(item => item.musicId === song.id)
        if (currentIndex !== -1) {
          this.$store.commit('player/SET_CURRENT_INDEX', currentIndex)
        }
        
        // 调用Vuex播放音乐
        this.$store?.dispatch('player/playMusic', {
          musicId: song.id,
          id: song.id,
          title: song.title,
          name: song.title,
          artist: song.artist,
          singer: song.artist,
          coverPath: song.cover,
          cover: song.cover,
          duration: song.duration,
          filePath: song.filePath,
          src: song.filePath
        })
        
        // 如果用户已登录，记录播放历史（异步，不阻塞播放）
        const userToken = localStorage.getItem('userToken')
        const userExpiry = localStorage.getItem('userTokenExpiry')
        if (userToken && userToken !== 'null' && userToken !== '' && userToken.length > 20 && userExpiry && Date.now() < parseInt(userExpiry)) {
          try {
            await playlistAPI.addPlayHistory(song.id)
          } catch (historyError) {
            console.warn('记录播放历史失败:', historyError)
            if (historyError.response?.status === 401 || historyError.response?.status === 403) {
              localStorage.removeItem('userToken')
              localStorage.removeItem('userInfo')
              localStorage.removeItem('userTokenExpiry')
            }
          }
        }
      } catch (error) {
        console.error('播放音乐失败:', error)
      }
    },
    
    async toggleFavorite(song) {
      try {
        // 构建音乐数据对象
        const musicData = {
          musicId: song.id,
          id: song.id,
          title: song.title,
          name: song.title,
          artist: song.artist,
          singer: song.artist,
          cover: song.cover,
          duration: song.duration,
          filePath: song.filePath
        }
        
        // 使用Vuex store的toggleFavorite action
        await this.$store.dispatch('player/toggleFavorite', musicData)
        
        console.log('收藏操作成功:', song.title)
      } catch (error) {
        console.error('收藏操作失败:', error)
      }
    },
    
    isFavorite(songId) {
      return this.$store.getters['player/favorites'].includes(songId)
    },
    
    getCategoryColor(categoryName) {
      const category = this.categories.find(cat => cat.name === categoryName)
      return category ? category.color : '#b3b3b3'
    },

    buildCoverUrl(coverPath) {
      if (!coverPath) return null
      if (coverPath.startsWith('http')) return coverPath
      return `${process.env.VUE_APP_API_BASE_URL || 'http://localhost:8080'}${coverPath}`
    },

    buildAudioUrl(filePath) {
      if (!filePath) return null
      if (filePath.startsWith('http')) return filePath
      return `${process.env.VUE_APP_API_BASE_URL || 'http://localhost:8080'}${filePath}`
    }
  }
}
</script>

<style scoped>
.search-scroll {
  height: 100%;
}

.search {
  color: #ffffff;
  padding-bottom: 24px; /* 确保底部有适当的间距 */
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.search-tips h2 {
  font-size: 32px;
  margin-bottom: 12px;
  color: #ffffff;
}

.search-tips p {
  font-size: 16px;
  color: #b3b3b3;
  margin-bottom: 40px;
}

.section-title {
  font-size: 24px;
  font-weight: 700;
  margin: 40px 0 20px 0;
  text-align: left;
  color: #ffffff;
}

/* 热门搜索 */
.hot-searches {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 40px;
  justify-content: flex-start;
}

.hot-search-tag {
  background: #2a2a2a;
  color: #ffffff;
  padding: 8px 16px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
}

.hot-search-tag:hover {
  background: #1DB954;
  transform: translateY(-2px);
}

/* 分类浏览 */
.browse-categories {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 40px;
}

.browse-card {
  background: linear-gradient(135deg, var(--bg-color), rgba(0,0,0,0.3));
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: transform 0.2s ease;
  position: relative;
  overflow: hidden;
  min-height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.browse-card:hover {
  transform: scale(1.05);
}

.category-emoji {
  font-size: 32px;
  margin-bottom: 12px;
}

.browse-card h4 {
  color: #ffffff;
  font-size: 18px;
  font-weight: 700;
  margin: 0;
}

/* 搜索结果 */
.results-title {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 8px;
  color: #ffffff;
}

.results-count {
  color: #b3b3b3;
  margin-bottom: 32px;
  font-size: 16px;
}

/* 歌曲表格 */
.songs-table {
  width: 100%;
}

.table-header {
  display: grid;
  grid-template-columns: 40px 1fr 120px 80px 100px;
  gap: 16px;
  padding: 16px 12px;
  border-bottom: 1px solid #2a2a2a;
  font-size: 14px;
  color: #b3b3b3;
  font-weight: 600;
  text-transform: uppercase;
}

.table-body {
  margin-top: 8px;
}

.song-row {
  display: grid;
  grid-template-columns: 40px 1fr 120px 80px 100px;
  gap: 16px;
  padding: 12px;
  border-radius: 8px;
  transition: all 0.2s ease;
  cursor: pointer;
  align-items: center;
}

.song-row:hover {
  background: #2a2a2a;
}

.song-index {
  text-align: center;
  color: #b3b3b3;
  font-size: 16px;
}

.song-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.song-thumbnail {
  width: 48px;
  height: 48px;
  flex-shrink: 0;
  border-radius: 4px;
  object-fit: cover;
}

.song-details {
  min-width: 0;
}

.song-title {
  color: #ffffff;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.song-artist {
  color: #b3b3b3;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.song-category {
  display: flex;
  justify-content: center;
}

.category-tag {
  background: #1DB954;
  color: #000000;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.song-duration {
  color: #b3b3b3;
  font-size: 14px;
  text-align: center;
}

.song-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.song-row:hover .song-actions {
  opacity: 1;
}

.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 50%;
  background: transparent;
  color: #b3b3b3;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  font-size: 14px;
}

.action-btn:hover {
  background: #404040;
  color: #ffffff;
  transform: scale(1.1);
}

.favorite-btn.favorited {
  color: #1DB954 !important;
}

.favorite-btn.favorited svg {
  color: #1DB954 !important;
}

.play-btn:hover {
  background: #1DB954;
  color: #000000;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #2a2a2a;
  border-top: 3px solid #1DB954;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 无结果状态 */
.no-results {
  text-align: center;
  padding: 60px 20px;
}

.no-results-icon {
  font-size: 64px;
  margin-bottom: 24px;
  opacity: 0.5;
}

.no-results h3 {
  font-size: 24px;
  margin-bottom: 12px;
  color: #ffffff;
}

.no-results p {
  color: #b3b3b3;
  margin-bottom: 32px;
}

.suggested-categories h4 {
  color: #ffffff;
  margin-bottom: 16px;
  font-size: 18px;
}

.category-suggestions {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: center;
}

.category-suggestion {
  background: #2a2a2a;
  color: #ffffff;
  padding: 8px 16px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
}

.category-suggestion:hover {
  background: #1DB954;
  color: #000000;
  transform: translateY(-2px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .table-header,
  .song-row {
    grid-template-columns: 30px 1fr 80px 60px;
  }
  
  .song-category {
    display: none;
  }
  
  .header-category {
    display: none;
  }
  
  .browse-categories {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
</style>